﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Windows.Data;
using Microsoft.Practices.Prism;
using Microsoft.Practices.Prism.Regions;
using YunBox2.Client.Infrastructure;
using YunBox2.Client.Infrastructure.ViewModels;
using YunBox2.Contracts;
using YunBox2.Contracts.FoundationModels;

using Microsoft.Practices.Prism.Events;
namespace YunBox2.Client.Foundation.ViewModels
{
	[Export]
	public class BoardMaterialViewModel : MainContentViewModel
	{
		private const string RightRegionName = "ReghtRegion";
		private const string EditorViewName = "BoarMaterialEditorView";
		private readonly ObservableCollection<BoardMaterial> _boardMaterialCollection;
		private readonly IFoundationService _foundationService = ClientContext.Current.FoundationService;

		[Import]
		private IRegionManager _regionManager;

		[Import]
		private IEventAggregator _eventAggregator;

		[ImportingConstructor]
		public BoardMaterialViewModel()
		{










			_boardMaterialCollection = new ObservableCollection<BoardMaterial>(_foundationService.GetAllBoardMaterialList(SessionContext.ClientID));
			BoardMaterialCollectionView = new ListCollectionView(_boardMaterialCollection);

			BoardMaterialCollectionView.CurrentChanged += (s, e) =>
				{
					if (BoardMaterialCollectionView.CurrentItem != null)
					{
						var boardMaterial = (BoardMaterial) BoardMaterialCollectionView.CurrentItem;
						if (boardMaterial.Id.HasValue)
						{
							var uriQuery = new UriQuery {{"id", boardMaterial.Id.Value.ToString("B")}};
							var uri = new Uri(EditorViewName + uriQuery.ToString());
							ScopeRegionManager.RequestNavigate(RightRegionName, uri);
						}
					}
				};
			BoardMaterialCollectionView.MoveCurrentToPosition(0);
		}


		public override string Title
		{
			get
			{
				return "纸板材质管理";
			}
		}

		public ICollectionView BoardMaterialCollectionView
		{
			get;
			private set;
		}

		public override bool IsShowEditButtons
		{
			get
			{
				return true;
			}
		}

		private void Create()
		{
		}

		private void Edit()
		{
		}

		private void Remove()
		{
			if (IsEditing)
			{
				return;
			}
			if (BoardMaterialCollectionView.CurrentItem == null)
			{
				return;
			}
			var boardMaterial = (BoardMaterial) BoardMaterialCollectionView.CurrentItem;
			if (boardMaterial.Id.HasValue)
			{
				if (_foundationService.RemoveBoardMaterialById(SessionContext.ClientID, boardMaterial.Id.Value))
				{
					BoardMaterialCollectionView.MoveCurrentToNext();
					_boardMaterialCollection.Remove(boardMaterial);
				}
			}
		}
	}
}